import React from 'react';
import { findDOMNode } from 'react-dom';
import $ from 'jquery';
import ZeroClipboard from 'zeroclipboard';

ZeroClipboard.config({
  swfPath: BlueWare.staticPath+"/resources/ZeroClipboard.swf"
});

export default class CopyClipboard extends React.Component{
  constructor(props, context) {
    super(props, context);

    this.state = {
      error: false
    }; // error
  }

  componentDidMount(){
    let el = findDOMNode(this);
    let client = this.client = new ZeroClipboard(el);
    let _this = this;

    client.on('ready',(initEvent) => {
      client.on('copy', () => client.setText(_this.props.text));
      client.on('aftercopy',
        this.props.onAfterCopy
          ? () => this.props.onAfterCopy(el)
          : () => {
              let $result = $('<i class="copied">已复制</i>');
              $(el).append($result);
              setTimeout(() => $result.fadeOut(() => $result.remove()), 1000);
            }
      );
    }); // ready

    client.on('error', event => {
      this.setState({
        error: true
      });
    }); // error
  }

  componentWillUnmount(){
    this.client.destroy()
  }

  render() {
    if (this.props.children && !this.state.error) {
      return this.props.children;
    } else {
      return null
    }
  }
}

CopyClipboard.defaultProps = {
  text:'Copy Text',
  onAfterCopy: null
}
